package cn.patient.pp.module.patients.service;

import cn.patient.pp.framework.security.core.LoginUser;
import cn.patient.pp.framework.security.core.util.SecurityFrameworkUtils;
import cn.patient.pp.module.patients.controller.admin.vo.*;
import cn.patient.pp.module.patients.dal.dataobject.patients.FollowUpDO;
import cn.patient.pp.module.patients.dal.dataobject.patients.PatientsDODO;
import cn.patient.pp.module.patients.dal.mysql.patients.FollowUpMapper;
import cn.patient.pp.module.patients.dal.mysql.patients.PatientsDOMapper;
import cn.patient.pp.module.system.dal.dataobject.dept.DeptDO;
import cn.patient.pp.module.system.dal.dataobject.dict.DictDataDO;
import cn.patient.pp.module.system.dal.dataobject.user.AdminUserDO;
import cn.patient.pp.module.system.service.dept.DeptService;
import cn.patient.pp.module.system.service.dict.DictDataService;
import cn.patient.pp.module.system.service.user.AdminUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DataComparisonServiceImpl implements DataComparisonService {

    @Resource
    private DeptService deptService;

    @Resource
    private PatientsDOMapper patientsDOMapper;

    @Resource
    private FollowUpMapper followUpMapper;

    @Resource
    private DictDataService dictDataService;

    @Resource
    private AdminUserService adminUserService;

    @Override
    public List<DataComparisonRespVO> getDataComparison(DataComparisonReqVO reqVO) {
        // 获取当前登录人
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO user = adminUserService.getUser(loginUser.getId());

        DeptDO dept = deptService.getDept(user.getDeptId());
        List<DeptDO> countyList = deptService.getDeptListByParentId(user.getDeptId());

        // 2. 解析时间区间（yyyyMMdd）
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDateTime start, end;
        String[] times = reqVO.getTimes();
        if (times != null && times.length == 2) {
            start = LocalDate.parse(times[0], DateTimeFormatter.BASIC_ISO_DATE).atStartOfDay();
            end   = LocalDate.parse(times[1], DateTimeFormatter.BASIC_ISO_DATE).atTime(LocalTime.MAX);
        } else {
            start = LocalDate.now().withDayOfMonth(1).atStartOfDay();
            end   = LocalDateTime.now();
        }
        String startStr = start.format(dtf);
        String endStr = end.format(dtf);

        // 3. 一次性拉取所有 dept_id 的指标
        List<DataComparisonRespVO> stats =
                followUpMapper.selectDataComparison(startStr, endStr);

        // 4. 遍历每个县，取该县所有子 deptId，然后累加 stats 中对应的值
        List<DataComparisonRespVO> result = new ArrayList<>(countyList.size());

        DataComparisonRespVO sum = new DataComparisonRespVO();
        sum.setDeptName(dept.getName());
        sum.setDeptId(dept.getId());
        long iSum = 0, cSum = 0, sSum = 0;
        result.add(sum);

        for (DeptDO county : countyList) {
            // 拿到“县下所有部门”ID（含自身）
            List<Long> subDeptIds = deptService.getDeptIdsAndOwnId(county.getId());

            long incSum  = stats.stream()
                    .filter(s -> subDeptIds.contains(s.getDeptId()))
                    .mapToLong(DataComparisonRespVO::getPatientIncreaseCount)
                    .sum();
            iSum+= incSum;

            long cureSum = stats.stream()
                    .filter(s -> subDeptIds.contains(s.getDeptId()))
                    .mapToLong(DataComparisonRespVO::getPatientCureCount)
                    .sum();
            cSum+= cureSum;

            long stopSum = stats.stream()
                    .filter(s -> subDeptIds.contains(s.getDeptId()))
                    .mapToLong(DataComparisonRespVO::getStoppingTreatmentCount)
                    .sum();
            sSum+= stopSum;

            DataComparisonRespVO vo = new DataComparisonRespVO();
            vo.setDeptId(county.getId());
            vo.setDeptName(county.getName());
            vo.setPatientIncreaseCount(incSum);
            vo.setPatientCureCount(cureSum);
            vo.setStoppingTreatmentCount(stopSum);
            result.add(vo);
        }
        // 5. 组装总和
        sum.setPatientIncreaseCount(iSum);
        sum.setPatientCureCount(cSum);
        sum.setStoppingTreatmentCount(sSum);

        return result;
    }

    @Override
    public PatientTypeStatsRespVO getPatientTypeStatistics(DataComparisonReqVO reqVO) {

        // ——— 1. dictType → 数据库列名 映射（Java 8 写法） ——
        Map<String, String> fieldMap = new HashMap<>();
        fieldMap.put("gender",     "gender");
        fieldMap.put("risk_assessment", "risk_assessment");
        
        // ——— 2. 时间格式化 ———
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDateTime start, end;
        String[] times = reqVO.getTimes();
        if (times != null && times.length == 2) {
            start = LocalDate.parse(times[0], DateTimeFormatter.BASIC_ISO_DATE).atStartOfDay();
            end   = LocalDate.parse(times[1], DateTimeFormatter.BASIC_ISO_DATE).atTime(LocalTime.MAX);
        } else {
            start = null;
            end   = null;
        }
        String startStr = null;
        if (start != null) {
            startStr = start.format(dtf);
        }
        String endStr   = null;
        if (end != null) {
            endStr = end.format(dtf);
        }

        String dictType = reqVO.getDictType();
        String fieldName = fieldMap.get(dictType);
        if (fieldName == null) {
            throw new IllegalArgumentException("不支持的 dictType: " + dictType);
        }

        reqVO.setDeptIds(getDeptIds(reqVO.getDeptId()));

        // ——— 3. 调用 Mapper 拉数据 ———
        Map<String,Object> params = new HashMap<>();
        params.put("deptIds",   reqVO.getDeptIds());
        params.put("start",     startStr);
        params.put("end",       endStr);
        params.put("fieldName", fieldName);

        Long total = patientsDOMapper.selectTotalPatientsByType(params);
        List<PatientTypeCountVO> counts =
                patientsDOMapper.selectPatientTypeCounts(params);

        // ——— 4. 组装返回 ———
        PatientTypeStatsRespVO resp = new PatientTypeStatsRespVO();
        resp.setTotalCount(total);
        resp.setTypeCounts(counts);
        return resp;
    }

    @Override
    public List<AgeCountVO> getPatientAgeStatistics(DataComparisonReqVO reqVO) {

        // ——— 1. 解析时间区间（yyyyMMdd） ———
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDateTime start, end;
        String[] times = reqVO.getTimes();
        if (times != null && times.length == 2) {
            start = LocalDate.parse(times[0], DateTimeFormatter.BASIC_ISO_DATE).atStartOfDay();
            end   = LocalDate.parse(times[1], DateTimeFormatter.BASIC_ISO_DATE).atTime(LocalTime.MAX);
        } else {
            start = null;
            end   = null;
        }
        String startStr = null;
        if (start != null) {
            startStr = start.format(dtf);
        }
        String endStr   = null;
        if (end != null) {
            endStr = end.format(dtf);
        }

        reqVO.setDeptIds(getDeptIds(reqVO.getDeptId()));

        // ——— 2. 组装参数 ———
        Map<String,Object> params = new HashMap<>();
        params.put("deptIds", reqVO.getDeptIds());
        params.put("start",   startStr);
        params.put("end",     endStr);

        // ——— 3. 调用 Mapper 获取各年龄统计 ———
        List<AgeCountVO> counts = patientsDOMapper.selectPatientAgeCounts(params);

        return counts;
    }

    // in DataComparisonServiceImpl.java

    @Override
    public PatientTypeStatsRespVO getOrgSubDbStatusStatistics(DataComparisonReqVO reqVO) {
        // ——— 1. dictType → 数据库列名 映射（Java 8 写法） ——
        Map<String, String> fieldMap = new HashMap<>();
        fieldMap.put("symptoms",     "current_symptoms_detail");
        fieldMap.put("insight", "insight");
        fieldMap.put("treatment_effect", "treatment_effect");
        fieldMap.put("sub_library_status","current_org_sub_db_status");
        // —— 1. 时间 & 科室 解析 ——
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDateTime start, end;
        String[] times = reqVO.getTimes();
        if (times != null && times.length == 2) {
            start = LocalDate.parse(times[0],dtf).atStartOfDay();
            end   = LocalDate.parse(times[1],dtf).atTime(LocalTime.MAX);
        } else {
            start = null;
            end   = null;
        }

        reqVO.setDeptIds(getDeptIds(reqVO.getDeptId()));

        String startStr = null;
        if (start != null) {
            startStr = start.format(dtf);
        }
        String endStr   = null;
        if (end != null) {
            endStr = end.format(dtf);
        }

        String dictType = reqVO.getDictType();
        String fieldName = fieldMap.get(dictType);
        if (fieldName == null) {
            throw new IllegalArgumentException("不支持的 dictType: " + dictType);
        }

        // —— 2. 组装参数 ——
        Map<String,Object> params = new HashMap<>();
        params.put("deptIds", reqVO.getDeptIds());
        params.put("start",   startStr);
        params.put("end",     endStr);
        params.put("fieldName", fieldName);

        // —— 3. 调用 Mapper ——
//        Long total = followUpMapper.selectTotalByOrgSubDbStatus(params);
        List<PatientTypeCountVO> counts =
                followUpMapper.selectOrgSubDbStatusCounts(params);

        // —— 4. 封装返回 ——
        PatientTypeStatsRespVO resp = new PatientTypeStatsRespVO();
        resp.setTotalCount((long) counts.size());
        resp.setTypeCounts(counts);
        return resp;
    }

    @Override
    public DangerBehaviorStatsVO getDangerBehaviorStatistics(DataComparisonReqVO reqVO) {
        // 时间与部门解析同前
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDateTime start, end;
        String[] times = reqVO.getTimes();
        if (times != null && times.length == 2) {
            start = LocalDate.parse(times[0], DateTimeFormatter.BASIC_ISO_DATE).atStartOfDay();
            end   = LocalDate.parse(times[1], DateTimeFormatter.BASIC_ISO_DATE).atTime(LocalTime.MAX);
        } else {
            start = null;
            end   = null;
        }
        String startStr = null;
        if (start != null) {
            startStr = start.format(dtf);
        }
        String endStr   = null;
        if (end != null) {
            endStr = end.format(dtf);
        }

        reqVO.setDeptIds(getDeptIds(reqVO.getDeptId()));

        Map<String,Object> params = new HashMap<>();
        params.put("deptIds", reqVO.getDeptIds());
        params.put("start",   startStr);
        params.put("end",     endStr);

        return followUpMapper.selectDangerBehaviorStats(params);
    }

    public List<Long> getDeptIds(Long inputDeptId) {
        // 获取当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO user = adminUserService.getUser(loginUser.getId());
        // 获取用户的部门 ID 列表
        List<Long> deptIds = deptService.getDeptIdsAndOwnId(user.getDeptId());
        if (inputDeptId == null || inputDeptId == 0) {
            return deptIds;
        } else {
            return deptService.getDeptIdsAndOwnId(inputDeptId);
        }
    }
}
